<script setup>
import LayoutHeader from "@/views/v-wkf-service/flow/wkf-design/layout/LayoutHeader.vue";
import BaseSetting from "@/views/v-wkf-service/flow/wkf-design/layout/BaseSetting.vue";
import {useFlowStore} from "@/store/modules/flow.js";
import {isNotEmpty} from "@/utils/index.js";
import router from "@/router/index.js";
import {useRoute} from "vue-router";
import {createForm, detail, updateFormDetail} from "@/api/v-wkf-service";
import ProcessDesign from "@/views/v-wkf-service/flow/wkf-design/layout/ProcessDesign.vue";
import FormDesign from "@/views/v-wkf-service/flow/wkf-design/layout/FormDesign.vue";
import ProSetting from "@/views/v-wkf-service/flow/wkf-design/layout/ProSetting.vue";
const route = useRoute();
const flowStore = useFlowStore()
const proxy = getCurrentInstance()

/**
 * data
 */
const isNew = ref(true)
const validStep = ref(0)
const timer = ref(null)
const activeSelect = ref('baseSetting')
const validVisible = ref(false)
const validResult = ref({})
const validOptions = ref([
  {title: '基础信息', description: '', icon: '', status: ''},
  {title: '审批表单', description: '', icon: '', status: ''},
  {title: '审批流程', description: '', icon: '', status: ''},
  {title: '扩展设置', description: '', icon: '', status: ''},
])
const validComponents = ref(['baseSetting', 'formDesign', 'processDesign', 'proSetting'])

/**
 * computed
 */
const setup = computed(() => flowStore.design);
const errTitle = computed(()=>{
  if (validResult.value.finished && validResult.value.success){
    return validResult.value.title + `(${validResult.value.errs.length}项错误)😥`
  }
  return validResult.value.title
})
const validIcon = computed(() => {
  if (!validResult.value.finished){
    return 'loading'
  }else if (validResult.value.success){
    return 'success'
  }else{
    return 'warning'
  }
})
/**
 * method
 */
const showValiding = () => {
  validResult.value = {
    errs: [],
    finished: false,
    success: false,
    title: '检查中...',
    action: '处理',
    desc: '正在检查设置项'
  }
  validStep.value = 0
  validOptions.value.forEach(op => {
    op.status = ''
    op.icon = ''
    op.description = ''
  })
}

const loadInitFrom = () => {
  flowStore.loadForm({
    formId: null,
    formName: "未命名表单",
    formKey: '',
    formUrl: '',
    logo: {
      icon: "el-icon-eleme",
      background: "#1e90ff"
    },
    settings: {
      commiter: [],
      admin: [],
      sign: false,
      notify: {
        types: [{type: "APP", name: "应用内通知"}],
        title: "消息通知标题"
      }
    },
    groupId: undefined,
    formItems: [],
    process: {
      id: "root",
      parentId: null,
      type: "ROOT",
      name: "发起人",
      desc: "任何人",
      props: {
        assignedUser: [],
        formPerms: []
      },
      children: {}
    },
    remark: "备注说明"
  })
}
const loadFormInfo = () => {
  detail(formId).then(({data}) => {
    let form = data;
    form.logo = JSON.parse(form.logo)
    form.settings = JSON.parse(form.settings)
    form.formItems = JSON.parse(form.formItems)
    form.process = JSON.parse(form.process)
    flowStore.loadForm(form)
  }).catch(err => {
    ElMessage({message: err, type: 'error',})
  })
}

const showValidFinish = (success, err) => {
  validResult.value.success = success
  validResult.value.finished = true
  validResult.value.title = success ? '校验完成 😀' : '校验失败 '
  validResult.value.desc = success ? '设置项校验成功，是否提交？' : err
  validResult.value.action = success ? '提 交' : '去修改'
}

const baseSetting = ref()
const validateDesign = () => {
  validVisible.value = true
  validStep.value = 0
  showValiding()
  stopTimer()
  timer.value = setInterval(() => {
    const fn = Object.assign({},proxy.refs[validComponents.value[validStep.value]])
    validResult.value.errs = fn.validate()
    if (Array.isArray(validResult.value.errs) && validResult.value.errs.length === 0) {
      validStep.value++;
      if (validStep.value >= validOptions.value.length) {
        stopTimer()
        showValidFinish(true)
      }
    } else {
      stopTimer()
      validOptions.value[validStep.value].status = 'error'
      showValidFinish(false, getDefaultValidErr())
    }
  }, 300)
}

const getDefaultValidErr = () => {
  switch (validStep.value) {
    case 0:
      return '请检查基础设置项';
    case 1:
      return '请检查审批表单相关设置'
    case 2:
      return '请检查审批流程，查看对应标注节点错误信息'
    case 3:
      return '请检查扩展设置'
    default:
      return '未知错误'
  }
}

const doAfter = () => {
  if (validResult.value.success) {
    doPublish()
  } else {
    activeSelect.value = validComponents.value[validStep.value]
    validVisible.value = false
  }
}

const preview = () => {
  validateDesign()
}

const publishProcess = () => {
  validateDesign()
}

const doPublish = () => {
  ElMessageBox.confirm('如果您只想预览请选择预览，确认发布后流程立即生效，是否继续?', '提示',
      {
        closeOnClickModal: false,
        confirmButtonText: '发布',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '拼命加载中...'
            let template = {
              formId: setup.value.formId,
              formName: setup.value.formName,
              formKey: setup.value.formKey,
              formUrl: setup.value.formUrl,
              logo: JSON.stringify(setup.value.logo),
              settings: JSON.stringify(setup.value.settings),
              groupId: setup.value.groupId,
              formItems: JSON.stringify(setup.value.formItems),
              process: JSON.stringify(setup.value.process),
              remark: setup.value.remark
            }
            if (isNew.value || !isNotEmpty(setup.value.formId)) {
              createForm(template).then(rsp => {
                ElMessage({message: '创建表单成功', type: 'success',})
                router.push("/flow-group")
                done()
              }).catch(err => {
                this.$message.error(err)
              })
            } else {
              updateFormDetail(template).then(rsp => {
                ElMessage({message: '更新表单成功', type: 'success',})
                router.push("/flow-group")
                done()
              }).catch(err => {
                ElMessage({message: err, type: 'error',})
              })
            }
          } else {
            done()
          }
        }
      }
  )
}

const stopTimer = () => {
  if (timer.value) clearInterval(timer.value)
}

showValiding()
const formId = route.query.code
//判断传参，决定是新建还是加载原始数据
loadInitFrom()
if (isNotEmpty(formId)){
  isNew.value = false
  loadFormInfo(formId)
}
const groupId = route.query.groupId
setup.value.groupId = isNotEmpty(groupId) ? groupId : null

onMounted(()=>{

})

onBeforeUnmount(()=> {
  stopTimer()
})


</script>

<template>
  <el-container>
    <el-header style="background: white">
      <layout-header v-model="activeSelect" @publish="publishProcess" @preview="preview"></layout-header>
    </el-header>
    <div class="layout-body">
      <base-setting ref="baseSetting" v-show="activeSelect === 'baseSetting'"/>
      <form-design ref="formDesign" v-show="activeSelect === 'formDesign'"/>
      <process-design ref="processDesign" v-show="activeSelect === 'processDesign'"/>
      <pro-setting ref="proSetting" v-show="activeSelect === 'proSetting'"/>
    </div>
    <v-dialog :show-btn="false" v-model="validVisible" title="设置项检查">
      <el-steps align-center :active="validStep" finish-status="success">
        <el-step v-for="(step, i) in validOptions" :title="step.title" :key="i"
                 :icon="step.icon" :status="step.status" :description="step.description"/>
      </el-steps>
      <el-result :icon="validIcon" :title="errTitle" :subTitle="validResult.desc">
        <template #icon>
          <i style="font-size: 30px" v-if="!validResult.finished" class="el-icon-loading"></i>
        </template>
        <template #sub-title>
          <div class="err-info" v-if="validResult.errs.length > 0">
            <v-ellipsis hover-tip v-for="(err, i) in validResult.errs" :key="i + '_err'" :content="err">
              <i slot="pre" class="el-icon-warning-outline"></i>
            </v-ellipsis>
          </div>
        </template>
        <template #extra>
          <el-button type="primary" v-if="validResult.finished" @click="doAfter">
            {{ validResult.action }}
          </el-button>
        </template>
      </el-result>
    </v-dialog>
  </el-container>
</template>

<style scoped lang="scss">
</style>